package com.teamclub.app.sservices.systemmanager

import io.ebean.{Ebean, ExpressionList}
import com.teamclub.app.sforms.{AppDomainInstanceForm, AppRoleForm}
import com.teamclub.domain.system.{AppDomainInstance, AppFuncTree, AppRole, AppSubjectUser}
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.{F, MD5}
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

import scala.collection.JavaConversions._


/**
  * Created by ilkkzm on 17-8-16.
  */
@Service
class AppDomainInstanceService {
  val logger = LoggerFactory.getLogger(classOf[AppDomainInstanceService])

  def expr(where: ExpressionList[AppDomainInstance], form: AppDomainInstanceForm) = {
    if(form.id != null) {
      where.eq("id", form.id)
    }
    if(StringUtils.isNotBlank(form.name)) {
      where.eq("name", form.name)
    }
    if(StringUtils.isNotBlank(form.appDomain)) {
      where.eq("appDomain", form.appDomain)
    }
    where.eq("isAdmin", 1)
  }

  def list(form: AppDomainInstanceForm): F.Either[Pager[AppDomainInstance], ErrorCode] = {
    var where = Ebean.find(classOf[AppDomainInstance]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def add(form: AppDomainInstanceForm): F.Either[AppDomainInstance, ErrorCode] = {
    var instance = new AppDomainInstance
    if(form.id != null) {
      instance = Ebean.find(classOf[AppDomainInstance], form.id)
    }
    if(instance == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    BeanUtils.copyProperties(form, instance)
    if(form.funcTreeRef == null) {
      val funcTreeList = Ebean.find(classOf[AppFuncTree]).where().eq("appDomain", form.appDomain).findList()
      val keys = funcTreeList.map(_.getId)
      instance.setFuncTreeRef(keys.mkString(","))
    }
    val trans = Ebean.beginTransaction()
    try {
      if(form.id != null) {
        instance.update()
      } else {
        instance.setIsAdmin(true)
        instance.setValidateDate(null)
        instance.save()
        val organNo = String.valueOf(24101000 + instance.getId)
        instance.setOrganNo(organNo)
        instance.setValidateDate(form.getValidateDate)
        instance.update()
        val role = geneAdminRole(form.getAppDomain, organNo, instance)
        geneAppSubjectUser(organNo, role.getId, form.getAppDomain, form)
      }
      trans.commit()
    } catch {
      case e: Exception => {
        logger.error("", e)
        trans.rollback()
        return F.Either.Right(ErrorCode.ref(e.getMessage))
      }
    } finally {
      trans.end()
    }

    return F.Either.Left(instance)
  }

  def geneAdminRole(domainKey: String, organNo: String, instance: AppDomainInstance): AppRole = {
    val role = new AppRole
    role.setName("管理员")
    role.setOrganNo(organNo)
    role.setRoleKey("admin")
    role.setFuncTreeRef(instance.getFuncTreeRef)
    role.save()
    role
  }

  def geneAppSubjectUser(organNo: String, appRole: Integer, domainKey: String, form: AppDomainInstanceForm): AppSubjectUser = {
    if(StringUtils.isNotBlank(form.telephone)) {
      val count = Ebean.find(classOf[AppSubjectUser]).where().eq("appDomain", domainKey).eq("telephone", form.telephone).eq("isAdmin", 1).findCount();
      if(count > 0 ) throw new Exception("该手机号已注册过")
    }
    val user = new AppSubjectUser
    user.setUserName(organNo)
    user.setAppDomain(domainKey)
    if(StringUtils.isNotBlank(form.realName)) {
      user.setRealName(form.realName)
    } else {
      user.setRealName("管理员")
    }
    if(StringUtils.isNotBlank(form.password)) {
      user.setUserPassword(form.password)
    } else {
      user.setUserPassword(MD5.md5Hex("admin123"))
    }
    if(StringUtils.isNotBlank(form.telephone)) {
      user.setTelephone(form.telephone)
    }
    if(StringUtils.isNotBlank(form.email)) {
      user.setEmail(form.email)
    }
    if(form.validateDate != null) {
      user.setValidateDate(form.validateDate)
    }
    user.setOrganNo(organNo)
    user.setRoleId(appRole)
    user.setIsAdmin(true)
    user.save()
    user
  }

  def del(form: AppDomainInstanceForm): F.Either[AppDomainInstance, ErrorCode] = {
    val instance = Ebean.find(classOf[AppDomainInstance], form.id)
    if(instance == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      instance.delete()
      F.Either.Left(instance)
    }
  }

}
